'''
“悦享保”个人癌症医疗保障计划
'''

import sys
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from urllib.parse import urlencode
from common.helper import Helper


class Spider( object ):

    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "悦享保个人癌症医疗保障计划"

    def genProductInfo(self):

        #年龄段
        years = [str(i) for i in range(45,81)]

        #投保免赔额 0免赔 10000免赔
        deductible = ["0","10000"]

        #额外责任险 planA 不加购 planB加购质子重离子险 planC 加购恶性肿瘤险 planD 全部加购
        plan = ["planA","planB","planC","planD"]

        #有无社保 Y 有社保 N 无社保
        socialSec = ["Y","N"]

        #生成数据
        for v in product( years,deductible,plan,socialSec ):

            self.mysql.cursor.execute( domain[self.name]["insert_sql"].format( v[0],v[1],v[2],v[3]))
            self.mysql._conn.commit()

            print("产品信息写入数据库成功")

    #执行爬虫
    def requestJson(self,dt=None):


        data = {

            "productCode":"YXB_GRAZYLBZJH",
            "plan": dt["plan"],
            "enterAge":dt["year"],
            "deductible":dt["deductible"],
            "socialSecurity":dt["socialSec"],

        }

        r = requests.post( url = domain[self.name]["url"] + urlencode( data ),headers=domain[self.name]["header"])

        if r.status_code == 200:

            totalPrice = Helper.decimalParse( r.json()["price"])

            #更新产品价格
            data = {

                "name":self.name,
                "id":dt["id"],
                "price":totalPrice
            }

            self.mysql.updatePrice( data )

        else:

            data = {

                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)

if __name__ == '__main__':

    s = Spider()

    s.main()


